package com.ruoyi.user.model.factory.impl;


import com.ruoyi.common.core.enums.CacheKey;
import com.ruoyi.common.core.pojo.vo.TokenVO;
import com.ruoyi.common.redis.cache.CacheTemplate;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.user.model.enums.LoginStrategy;
import com.ruoyi.user.model.factory.LoginFactory;
import com.ruoyi.user.model.pojo.entity.User;
import com.ruoyi.user.model.pojo.request.app.LoginRequest;
import com.ruoyi.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import java.util.Map;

@Component
public class LoginFactoryPasswordImpl implements LoginFactory {
    private final IUserService iUserService;
    @Autowired
    private TokenService tokenService;

    public LoginFactoryPasswordImpl(IUserService iUserService) {
        this.iUserService = iUserService;
    }

    @Override
    public TokenVO<String> login(LoginRequest loginRequest){
        User one = iUserService.loginVerify(loginRequest.getPhone());
        Assert.isTrue(!StringUtils.isEmpty(one.getPassword()), "请先设置密码");
        PasswordEncoder passwordEncoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
        Assert.isTrue(passwordEncoder.matches(loginRequest.getSecretKey() + one.getSalt(), one.getPassword()), "账号或密码错误!");

        User cacheUser = CacheTemplate.getCache(CacheKey.USER_INFO.getKey(String.valueOf(one.getId())), User.class, () -> {
            CacheTemplate.setCache(CacheKey.USER_INFO.getKey(String.valueOf(one.getId())), one);
            return one;
        });

        Map<String, Object> appToken = tokenService.createAppToken(one.getId(), one.getNickName(), one.getStatus());
        String authorization = (String) appToken.get("access_token");
        return TokenVO.<String>builder()
                .nickname(cacheUser.getNickName())
                .id(String.valueOf(cacheUser.getId()))
                .authorization(authorization)
                .other(cacheUser.getPhone())
                .avatarUrl(cacheUser.getPhoto())
                .loginEnum(loginRequest.getLoginEnum())
                .rongYunToken(one.getRongToken())
                .isAuthentication(one.getIsAuth())
                .build();
    }

    @Override
    public LoginStrategy getStrategy() {
        return LoginStrategy.PASSWORD;
    }
}
